package com.carbohydrate42.kotlin_compose_demo.compose

import android.util.Log
import android.widget.Button
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
import com.carbohydrate42.kotlin_compose_demo.constant.Common

/**
 * 让 compose 和 view 进行交互
 */
@Preview(showSystemUi = true, showBackground = true)
@Composable
fun TryViewInCompose() {
    val current = LocalContext.current

    var count by remember { mutableStateOf(1) }

    Column {

        Button(onClick = {
            Log.d(Common.ANDROID_LOG_TAG.label, "compose button clicked")
            count++
        }) {
            Text(text = "compose button $count")
        }

        AndroidView(factory = {
            Button(current).apply {
                setOnClickListener {
                    Log.d(Common.ANDROID_LOG_TAG.label, "view button clicked")
                    count++
                }
            }
        }) {
            // 每次 compose 更新的时候会调用这个函数, 这样 view 也可以响应式了
            it.text = "view button $count"
        }
    }
}